package com.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.utils.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.annotation.IgnoreAuth;
import com.entity.OrdersEntity;
import com.service.OrdersService;

import com.entity.YanchupiaowuEntity;
import com.entity.view.YanchupiaowuView;

import com.service.YanchupiaowuService;
import com.service.TokenService;
import com.utils.PageUtils;
import com.utils.R;
import com.utils.MPUtil;
import com.utils.MapUtils;
import com.utils.CommonUtil;
import java.io.IOException;
import com.service.StoreupService;
import com.entity.StoreupEntity;

/**
 * 演出票务
 * 后端接口
 */
@RestController
@RequestMapping("/yanchupiaowu")
public class YanchupiaowuController {
    @Autowired
    private YanchupiaowuService yanchupiaowuService;

    @Autowired
    private StoreupService storeupService;

    @Autowired
    private OrdersService ordersService;

    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params,YanchupiaowuEntity yanchupiaowu,
                  @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date kaichangshijianstart,
                  @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date kaichangshijianend,
                  @RequestParam(required = false) Double pricestart,
                  @RequestParam(required = false) Double priceend,
                  HttpServletRequest request){
        EntityWrapper<YanchupiaowuEntity> ew = new EntityWrapper<YanchupiaowuEntity>();
        if(kaichangshijianstart!=null) ew.ge("kaichangshijian", kaichangshijianstart);
        if(kaichangshijianend!=null) ew.le("kaichangshijian", kaichangshijianend);
        if(pricestart!=null) ew.ge("price", pricestart);
        if(priceend!=null) ew.le("price", priceend);

        PageUtils page = yanchupiaowuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, yanchupiaowu), params), params));

        return R.ok().put("data", page);
    }

    /**
     * 前端列表
     */
    @IgnoreAuth
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,YanchupiaowuEntity yanchupiaowu,
                  @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date kaichangshijianstart,
                  @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date kaichangshijianend,
                  @RequestParam(required = false) Double pricestart,
                  @RequestParam(required = false) Double priceend,
                  HttpServletRequest request){
        EntityWrapper<YanchupiaowuEntity> ew = new EntityWrapper<YanchupiaowuEntity>();
        if(kaichangshijianstart!=null) ew.ge("kaichangshijian", kaichangshijianstart);
        if(kaichangshijianend!=null) ew.le("kaichangshijian", kaichangshijianend);
        if(pricestart!=null) ew.ge("price", pricestart);
        if(priceend!=null) ew.le("price", priceend);

        PageUtils page = yanchupiaowuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, yanchupiaowu), params), params));
        return R.ok().put("data", page);
    }



    /**
     * 列表
     */
    @RequestMapping("/lists")
    public R list( YanchupiaowuEntity yanchupiaowu){
        EntityWrapper<YanchupiaowuEntity> ew = new EntityWrapper<YanchupiaowuEntity>();
        ew.allEq(MPUtil.allEQMapPre( yanchupiaowu, "yanchupiaowu"));
        return R.ok().put("data", yanchupiaowuService.selectListView(ew));
    }

    /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(YanchupiaowuEntity yanchupiaowu){
        EntityWrapper< YanchupiaowuEntity> ew = new EntityWrapper< YanchupiaowuEntity>();
        ew.allEq(MPUtil.allEQMapPre( yanchupiaowu, "yanchupiaowu"));
        YanchupiaowuView yanchupiaowuView =  yanchupiaowuService.selectView(ew);
        return R.ok("查询演出票务成功").put("data", yanchupiaowuView);
    }

    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        YanchupiaowuEntity yanchupiaowu = yanchupiaowuService.selectById(id);
        yanchupiaowu.setClicknum(yanchupiaowu.getClicknum()+1);
        yanchupiaowu.setClicktime(new Date());
        yanchupiaowuService.updateById(yanchupiaowu);
        yanchupiaowu = yanchupiaowuService.selectView(new EntityWrapper<YanchupiaowuEntity>().eq("id", id));
        return R.ok().put("data", yanchupiaowu);
    }

    /**
     * 前端详情
     */
    @IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id){
        YanchupiaowuEntity yanchupiaowu = yanchupiaowuService.selectById(id);
        yanchupiaowu.setClicknum(yanchupiaowu.getClicknum()+1);
        yanchupiaowu.setClicktime(new Date());
        yanchupiaowuService.updateById(yanchupiaowu);
        yanchupiaowu = yanchupiaowuService.selectView(new EntityWrapper<YanchupiaowuEntity>().eq("id", id));
        return R.ok().put("data", yanchupiaowu);
    }



    /**
     * 赞或踩
     */
    @RequestMapping("/thumbsup/{id}")
    public R vote(@PathVariable("id") String id,String type){
        YanchupiaowuEntity yanchupiaowu = yanchupiaowuService.selectById(id);
        if(type.equals("1")) {
            yanchupiaowu.setThumbsupnum(yanchupiaowu.getThumbsupnum()+1);
        } else {
            yanchupiaowu.setCrazilynum(yanchupiaowu.getCrazilynum()+1);
        }
        yanchupiaowuService.updateById(yanchupiaowu);
        return R.ok("投票成功");
    }

    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody YanchupiaowuEntity yanchupiaowu, HttpServletRequest request){
        //ValidatorUtils.validateEntity(yanchupiaowu);
        yanchupiaowuService.insert(yanchupiaowu);
        return R.ok();
    }

    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody YanchupiaowuEntity yanchupiaowu, HttpServletRequest request){
        //ValidatorUtils.validateEntity(yanchupiaowu);
        yanchupiaowuService.insert(yanchupiaowu);
        return R.ok();
    }





    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody YanchupiaowuEntity yanchupiaowu, HttpServletRequest request){
        //ValidatorUtils.validateEntity(yanchupiaowu);
        yanchupiaowuService.updateById(yanchupiaowu);//全部更新
        return R.ok();
    }





    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        yanchupiaowuService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }


    /**
     * 前端智能排序
     */
    @IgnoreAuth
    @RequestMapping("/autoSort2")
    public R autoSort(@RequestParam Map<String, Object> params,YanchupiaowuEntity yanchupiaowu, HttpServletRequest request,String pre){
        EntityWrapper<YanchupiaowuEntity> ew = new EntityWrapper<YanchupiaowuEntity>();
        Map<String, Object> newMap = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String key = entry.getKey();
            String newKey = entry.getKey();
            if (pre.endsWith(".")) {
                newMap.put(pre + newKey, entry.getValue());
            } else if (StringUtils.isEmpty(pre)) {
                newMap.put(newKey, entry.getValue());
            } else {
                newMap.put(pre + "." + newKey, entry.getValue());
            }
        }
        params.put("sort", "clicknum");
        params.put("order", "desc");
        PageUtils page = yanchupiaowuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, yanchupiaowu), params), params));
        return R.ok().put("data", page);
    }


    /**
     * 协同算法（按用户购买推荐）
     */
    @RequestMapping("/autoSort1")
    public R autoSort2(@RequestParam Map<String, Object> params,YanchupiaowuEntity yanchupiaowu, HttpServletRequest request){
        String userId = request.getSession().getAttribute("userId").toString();
        String goodtypeColumn = "piaowuleixing";
        List<OrdersEntity> orders = ordersService.selectList(new EntityWrapper<OrdersEntity>().eq("userid", userId).eq("tablename", "yanchupiaowu").orderBy("addtime", false));
        List<String> goodtypes = new ArrayList<String>();
        Integer limit = params.get("limit")==null?10:Integer.parseInt(params.get("limit").toString());
        List<YanchupiaowuEntity> yanchupiaowuList = new ArrayList<YanchupiaowuEntity>();
        //去重
        List<OrdersEntity> ordersDist = new ArrayList<OrdersEntity>();
        for(OrdersEntity o1 : orders) {
            boolean addFlag = true;
            for(OrdersEntity o2 : ordersDist) {
                if(o1.getGoodid()==o2.getGoodid() || o1.getGoodtype().equals(o2.getGoodtype())) {
                    addFlag = false;
                    break;
                }
            }
            if(addFlag) ordersDist.add(o1);
        }
        if(ordersDist!=null && ordersDist.size()>0) {
            for(OrdersEntity o : ordersDist) {
                yanchupiaowuList.addAll(yanchupiaowuService.selectList(new EntityWrapper<YanchupiaowuEntity>().eq(goodtypeColumn, o.getGoodtype())));
            }
        }
        EntityWrapper<YanchupiaowuEntity> ew = new EntityWrapper<YanchupiaowuEntity>();
        params.put("sort", "id");
        params.put("order", "desc");
        PageUtils page = yanchupiaowuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, yanchupiaowu), params), params));
        List<YanchupiaowuEntity> pageList = (List<YanchupiaowuEntity>)page.getList();
        if(yanchupiaowuList.size()<limit) {
            int toAddNum = (limit-yanchupiaowuList.size())<=pageList.size()?(limit-yanchupiaowuList.size()):pageList.size();
            for(YanchupiaowuEntity o1 : pageList) {
                boolean addFlag = true;
                for(YanchupiaowuEntity o2 : yanchupiaowuList) {
                    if(o1.getId().intValue()==o2.getId().intValue()) {
                        addFlag = false;
                        break;
                    }
                }
                if(addFlag) {
                    yanchupiaowuList.add(o1);
                    if(--toAddNum==0) break;
                }
            }
        } else if(yanchupiaowuList.size()>limit) {
            yanchupiaowuList = yanchupiaowuList.subList(0, limit);
        }
        page.setList(yanchupiaowuList);
        return R.ok().put("data", page);
    }


}
